<?php
require 'helper/Db.php';
require 'helper/helper.php';

error_reporting(0);
$jsonData = file_get_contents('php://input');
$data = json_decode($jsonData, true);
$action = htmlentities($data['action']);
$email = htmlentities($data['email']);

$pattern = "/^\S+@\S+\.\S+$/";
if (!preg_match($pattern, $email)) {
    jsonReturn(['code' => 1, 'msg' => '邮箱格式不正确']);
}

$db = new Db();
switch ($action) {
    case 'login':
        $password = htmlentities(trim($data['password']));
        $password = rsaDecrypt($password);
        if (empty($email) || empty($password)) {
            jsonReturn(['code' => 1, 'msg' => '参数不全']);
        }
        $query = "select * from users where email = :email and enable = 1";
        $result = $db->query1($query, [':email' => ['data' => $email]]);
        if (!$result) {
            jsonReturn(['code' => 1, 'msg' => '无此用户']);
        } else {
            $user = $result[0];
            $pwd = md5($password . $user['salt']);
            if ($pwd != $user['password']) {
                jsonReturn(['code' => 1, 'msg' => '密码不匹配']);
            } else {
                jsonReturn(['code' => 0, 'msg' => '登录成功']);
            }
        }
    case 'getUser':
        $query = "select * from users where email = :email and enable = 1";
        $result = $db->query1($query, [':email' => ['data' => $email]]);
        if (!$result) {
            jsonReturn(['code' => 1, 'msg' => '无此用户']);
        } else {
            $user = $result[0];
            jsonReturn(['code' => 0, 'msg' => $result[0]]);
        }
        break;
    case 'deleteUser':
        $query = "delete from users where email = :email";
        $affectRow = $db->execute($query, [':email' => $email]);
        if ($affectRow > 0) {
            jsonReturn(['code' => 0, 'msg' => '删除成功']);
        } else {
            jsonReturn(['code' => 1, 'msg' => '删除失败']);
        }
        break;
    case 'updateUser':
        $user_name = htmlentities(trim($data['user_name']));
        if (empty($user_name)) {
            jsonReturn(['code' => 1, 'msg' => '用户名不能为空']);
        }
        $query = "update users set user_name = :user_name where email = :email";
        $affectRow = $db->execute($query, [':email' => $email, ':user_name' => $user_name]);
        if ($affectRow > 0) {
            jsonReturn(['code' => 0, 'msg' => '修改成功']);
        } else {
            jsonReturn(['code' => 1, 'msg' => '修改失败']);
        }
        break;
    default:
        jsonReturn(['code' => 1, 'msg' => '错误的请求']);
        break;
}
